package com.example.stock.controller;

import com.example.stock.excel.Finance;
import com.example.stock.service.FinanceDataService;
import com.example.stock.util.Result;
import com.example.stock.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("finance")
public class FinanceController {

    @Autowired
    FinanceDataService financeDataService;

    @GetMapping("stat/{date}")
    public Result index(@PathVariable String date) {

        List<Finance> finances = financeDataService.getSesFinanceData().get(date);
        return ResultGenerator.genSuccessResult(Map.of(
                "dates", financeDataService.getSesFinanceData().keySet().stream().sorted(Comparator.comparing(String::toString).reversed()).toList(),
                "data", finances));
    }

    @GetMapping("stock/{stock}")
    public Result stockData(@PathVariable String stock) {
        List<Finance> finances = financeDataService.getStockFinanceData().get(stock);

        // 按年分组
        Map<String, List<Finance>> collect = finances.stream()
                .sorted(Comparator.comparing(Finance::getSes).reversed())
                .collect(Collectors.groupingBy(item -> item.getSes().substring(0, 4)));

        return ResultGenerator.genSuccessResult(collect);
    }

    @GetMapping("totalOperatingRevenue")
    public Result totalOperatingRevenue() {
        return ResultGenerator.genSuccessResult(financeDataService.getTotalOperatingRevenueList());
    }

    @GetMapping("roe")
    public Result roe() {
        return ResultGenerator.genSuccessResult(financeDataService.getRoeList());
    }

    @GetMapping("adjustedProfit")
    public Result adjustedProfit() {
        return ResultGenerator.genSuccessResult(financeDataService.getAdjustedProfitList());
    }

    @GetMapping("grossProfitMargin")
    public Result grossProfitMargin() {
        return ResultGenerator.genSuccessResult(financeDataService.getGrossProfitMarginList());
    }

    @GetMapping("netProfitMargin")
    public Result netProfitMargin() {
        return ResultGenerator.genSuccessResult(financeDataService.getNetProfitMarginList());
    }

    @GetMapping("liabilityOnAssetRatio")
    public Result liabilityOnAssetRatio() {
        return ResultGenerator.genSuccessResult(financeDataService.getLiabilityOnAssetRatioList());
    }

    @GetMapping("incTotalRevenueYearOnYear")
    public Result incTotalRevenueYearOnYear() {
        return ResultGenerator.genSuccessResult(financeDataService.getIncTotalRevenueYearOnYearList());
    }
}
